package com.scd.sign;

import cn.hutool.crypto.digest.DigestUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class SignUtil {

    /**
     * appId=appId&appKey=appKey&timeStamp=当前时间戳&body=json参数
     * appId=appId&appKey=appKey&timeStamp=当前时间戳&key1=value1&key2=value2,key 按照升序排列
     * @param appId app id
     * @param appKey app secret
     * @param timestamp timestamp
     * @param param param
     * @return sign
     */
    public static String generateBodySign(String appId, String appKey,
                                          String timestamp, String param) {
        String paramEncode;
        try {
            paramEncode = URLEncoder.encode(param, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("appId=").append(appId)
                .append("&appKey=").append(appKey)
                .append("&timeStamp=").append(timestamp)
                .append("&body=").append(paramEncode);
        return DigestUtil.sha512Hex(stringBuilder.toString(), StandardCharsets.UTF_8.name());

    }
}
